#include <QDebug>
#include "cmytcpserver.h"
#define UNUSED -1
CMyTCPServer::CMyTCPServer(QObject *parent) :
    QTcpServer(parent)
{
    int i = 0;
    m_tcpSet.localIP = "";
    for (i=0; i<CLIENTCOUNT; i++)
    {
        m_tcpClient[i].socketDescriptor = UNUSED;
    }
}

void CMyTCPServer::SetParam(TCPSSetStruct set)
{
    if (set.localIP.isEmpty())
        return ;
    m_tcpSet = set;
}

bool CMyTCPServer::OpenTcpS()
{
    if (!isListening() && !listen(QHostAddress(m_tcpSet.localIP), m_tcpSet.localPort))
    {
        close();
        return false;
    }
    m_flag = true;
    return m_flag;
}

void CMyTCPServer::CloseTcpS()
{
    int i = 0;
    for (i=0; i<CLIENTCOUNT; i++)
    {
        m_tcpClient[i].socketDescriptor = UNUSED;
        m_tcpClient[i].tcpConn.close();
    }
    close();
}

bool CMyTCPServer::IsConnected()
{
    return m_flag;
}

TCPSSetStruct CMyTCPServer::GetParam()
{
    return m_tcpSet;
}

int CMyTCPServer::FindSocket(QString ip, quint16 port)
{
    int i = 0;
    for (i=0; i<CLIENTCOUNT; i++)
    {
        if (m_tcpClient[i].socketDescriptor > 0)
        {
            if ((ip == m_tcpClient[i].ip) && (port == m_tcpClient[i].port))
                return i;
        }
    }
    return -1;
}

int CMyTCPServer::SendData(const char *data, int len, QString ip, quint16 port)
{
    int i = 0;
    if (data == NULL)
        return 0;
    i = FindSocket(ip, port);
    if (i >= 0)
    {
        return m_tcpClient[i].tcpConn.write(data,len);
    }
    return 0;
}

void CMyTCPServer::processPendingDatagrams()
{
    QByteArray buff;
    QTcpSocket *tcpClient = (QTcpSocket *)QObject::sender();
    QString ip;
    quint16 port;

    while (tcpClient->bytesAvailable())
    {
        buff = tcpClient->readAll();
        ip = tcpClient->peerAddress().toString();
        port = tcpClient->peerPort();
        emit sigReceiveMsg(buff.data(), buff.count(), ip, port);
//        qDebug("orignl data: %s", buff.data());
    }
}

void CMyTCPServer::deleteConnection()
{
    int i = 0;
    QTcpSocket *tcpClient = (QTcpSocket *)QObject::sender();
    QString ip;
    quint16 port;
    ip = tcpClient->peerAddress().toString();
    port = tcpClient->peerPort();
    i = FindSocket(ip, port);
    if (i >= 0)
    {
        m_tcpClient[i].ip = "";
        m_tcpClient[i].socketDescriptor = UNUSED;
        m_tcpClient[i].tcpConn.close();
        emit sigDeleteConnection(ip, port);
//        qDebug()<<"DISCONECT:"<<ip<<"PORT:"<<port;
    }
}
//如果有新连接到来，触发此函数
void CMyTCPServer::incomingConnection(qintptr socketDescriptor)
{
    int i = 0;
    QString iptemp;
    quint16 porttemp;
    for (i=0; i<CLIENTCOUNT; i++)
    {
        if (m_tcpClient[i].socketDescriptor == UNUSED)
        {
            m_tcpClient[i].socketDescriptor = socketDescriptor;
            m_tcpClient[i].tcpConn.setSocketDescriptor(socketDescriptor);
            iptemp = m_tcpClient[i].tcpConn.peerAddress().toString();
            porttemp = m_tcpClient[i].tcpConn.peerPort();
            m_tcpClient[i].ip = iptemp;
            m_tcpClient[i].port = porttemp;

            connect(&(m_tcpClient[i].tcpConn), SIGNAL(readyRead()),
                    this, SLOT(processPendingDatagrams()));
            connect(&(m_tcpClient[i].tcpConn), SIGNAL(disconnected()),
                    this, SLOT(deleteConnection()));

            emit sigComingConnection(iptemp, porttemp);
//            qDebug()<<"CONNECT ip:"<<iptemp<<" PORT: "<<porttemp;
            break;
        }
    }
}
